package com.trmp.base.shoppingMng.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Pageable;

import com.trmp.base.shoppingMng.entity.BaseShoppingStoreInfo;
import com.trmp.base.shoppingMng.entity.BaseShoppingStoreInfo_;

public class ShoppingStoreInfoDaoImpl {
	@PersistenceContext
	private EntityManager em;
	public List<BaseShoppingStoreInfo> search(Long orgId,String name,String address,Pageable page)
	{
		 
	    
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<BaseShoppingStoreInfo> cq = cb.createQuery(BaseShoppingStoreInfo.class);
		Root<BaseShoppingStoreInfo> root = cq.from(BaseShoppingStoreInfo.class); 
		cq.select(cb.construct(BaseShoppingStoreInfo.class, root.get("shoppingId"),
				 root.get("cmpName"),root.get("cmpAdd"),root.get("chiffMobile")
				));
		if(("".equals(name)&&"".equals(address))||(null==name&&null==address))
		{
			cq.where(cb.and(cb.equal(root.get("orgID"),orgId)
					));
		}else
		if("".equals(name))
		{
			cq.where(cb.and(cb.equal(root.get(BaseShoppingStoreInfo_.orgID),orgId),
					cb.like(root.get(BaseShoppingStoreInfo_.cmpAdd), "%"+address+"%")
					));
		}else
		if("".equals(address))
		{
			cq.where(cb.and(cb.equal(root.get(BaseShoppingStoreInfo_.orgID),orgId),
					cb.like(root.get(BaseShoppingStoreInfo_.cmpName), "%"+name+"%")
					));
		}else{
			cq.where(cb.and(cb.equal(root.get(BaseShoppingStoreInfo_.orgID),orgId),
					cb.like(root.get(BaseShoppingStoreInfo_.cmpName), "%"+name+"%"),
					cb.like(root.get(BaseShoppingStoreInfo_.cmpAdd), "%"+address+"%")
					));
		}
		Query query= em.createQuery(cq);
		query.setFirstResult(page.getPageNumber()*page.getPageSize()).setMaxResults(page.getPageSize()); 
		return query.getResultList();
		
	}
}
